package com.lakala.management.test.converter;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.beanutils.PropertyUtils;

import org.dozer.DozerConverter;
import org.dozer.Mapper;

import com.lakala.core.vo.QueryBean;



public class QueryBeanConverter extends DozerConverter<Object, QueryBean> {
	private Mapper mapper;

	public QueryBeanConverter() {
		//SqlSession
		super(Object.class, QueryBean.class);
	}

	@Override
	public QueryBean convertTo(Object source, QueryBean destination) {
		if (source == null) {
			// return (Collections.EMPTY_MAP);
			return (new QueryBean());
		}
		if(null==destination){
			destination = new QueryBean();
		}
		PropertyDescriptor[] descriptors = BeanUtilsBean.getInstance()
				.getPropertyUtils().getPropertyDescriptors(source);
		Class clazz = source.getClass();
		try {
			for (int i = 0; i < descriptors.length; i++) {
				String name = descriptors[i].getName();
				if (getReadMethod(clazz, descriptors[i]) != null) {

					Object property = PropertyUtils.getProperty(source, name);
							
					destination.put(name, property);

				}
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		return (destination);
	}

	@Override
	public Object convertFrom(QueryBean source, Object destination) {
		mapper.map(source, destination);
		return destination;
	}

	public void setMapper(Mapper mapper) {
		this.mapper = mapper;
	}

	private Method getReadMethod(Class clazz, PropertyDescriptor descriptor) {
		return (MethodUtils.getAccessibleMethod(clazz,
				descriptor.getReadMethod()));
	}
}
